import { Province } from "../models/Province.mjs";
/**
 * 分析地区发展趋势
 * @param {string} provinceName - 省份名称
 * @returns {Object} 包含各维度历年数据的对象
 */
async function analyzeProvinceTrend(provinceName) {
  try {
    // 获取省份数据
    const province = await Province.findOne({ name: provinceName });
    if (!province) {
      throw new Error(`未找到省份: ${provinceName}`);
    }

    // 定义需要分析的维度
    const dimensions = {
      GDP: {
        name: "GDP",
        unit: "亿元",
        description: "GDP增长趋势",
      },
      employment: {
        name: "employment",
        unit: "万人",
        description: "就业人数变化",
      },
      income: {
        name: "income",
        unit: "元",
        description: "居民人均可支配收入",
      },
      cost: {
        name: "cost",
        unit: "元",
        description: "居民消费支出",
      },
      edFund: {
        name: "edFund",
        unit: "万元",
        description: "教育经费投入",
      },
    };

    // 处理各维度数据
    const result = {};
    for (const [key, dim] of Object.entries(dimensions)) {
      const statistic = province.statistics.find((s) => s.name === dim.name);
      if (statistic && statistic.yearlyData) {
        // 按年份排序
        const yearlyData = [...statistic.yearlyData]
          .filter((d) => d.value > 0) // 过滤无效数据
          .sort((a, b) => a.year - b.year); // 按年份升序

        // 计算同比增长率
        const growthRates = yearlyData.map((data, index) => {
          if (index === 0)
            return { year: data.year, value: data.value, growth: 0 };
          const previousValue = yearlyData[index - 1].value;
          const growth = ((data.value - previousValue) / previousValue) * 100;
          return {
            year: data.year,
            value: Math.round(data.value),
            growth: Number(growth.toFixed(2)),
          };
        });

        result[key] = {
          name: dim.description,
          unit: dim.unit,
          data: growthRates,
          trend: analyzeTrend(growthRates),
          summary: generateSummary(growthRates, dim),
        };
      }
    }

    return result;
  } catch (error) {
    console.error("分析地区发展趋势时出错:", error);
    throw error;
  }
}

/**
 * 分析数据趋势
 * @param {Array} data - 年度数据数组
 * @returns {string} 趋势描述
 */
function analyzeTrend(data) {
  if (data.length < 2) return "数据不足以分析趋势";

  const recentYears = data.slice(-3); // 取最近三年
  const growths = recentYears.map((d) => d.growth);
  const avgGrowth = growths.reduce((sum, g) => sum + g, 0) / growths.length;

  if (avgGrowth > 5) return "快速增长";
  if (avgGrowth > 2) return "稳定增长";
  if (avgGrowth > 0) return "缓慢增长";
  if (avgGrowth > -2) return "略有下降";
  return "明显下降";
}

/**
 * 生成数据摘要
 * @param {Array} data - 年度数据数组
 * @param {Object} dimension - 维度信息
 * @returns {Object} 数据摘要
 */
function generateSummary(data, dimension) {
  const latest = data[data.length - 1];
  const maxValue = Math.max(...data.map((d) => d.value));
  const maxGrowth = Math.max(...data.map((d) => d.growth));
  const avgGrowth = data.reduce((sum, d) => sum + d.growth, 0) / data.length;

  return {
    latestValue: `${Math.round(latest.value)} ${dimension.unit}`,
    latestYear: latest.year,
    maxValue: `${Math.round(maxValue)} ${dimension.unit}`,
    maxGrowth: `${Math.round(maxGrowth)}%`,
    avgGrowth: `${Math.round(avgGrowth)}%`,
  };
}

/**
 * 分析全国平均趋势
 * @returns {Object} 包含全国平均各维度历年数据的对象
 */
async function analyzeNationalTrend() {
  try {
    // 获取所有省份数据
    const provinces = await Province.find({});
    
    // 定义需要分析的维度
    const dimensions = {
      GDP: {
        name: "GDP",
        unit: "亿元",
        description: "GDP增长趋势",
      },
      employment: {
        name: "employment",
        unit: "万人",
        description: "就业人数变化",
      },
      income: {
        name: "income",
        unit: "元",
        description: "居民人均可支配收入",
      },
      cost: {
        name: "cost",
        unit: "元",
        description: "居民消费支出",
      },
      edFund: {
        name: "edFund",
        unit: "万元",
        description: "教育经费投入",
      },
    };

    // 处理各维度数据
    const result = {};
    for (const [key, dim] of Object.entries(dimensions)) {
      // 收集所有省份的该维度数据
      let allYearData = new Map(); // year -> [values]
      
      provinces.forEach(province => {
        const statistic = province.statistics.find(s => s.name === dim.name);
        if (statistic && statistic.yearlyData) {
          statistic.yearlyData
            .filter(d => d.value > 0)
            .forEach(d => {
              if (!allYearData.has(d.year)) {
                allYearData.set(d.year, []);
              }
              allYearData.get(d.year).push(d.value);
            });
        }
      });

      // 计算每年的平均值
      const yearlyData = Array.from(allYearData.entries())
        .map(([year, values]) => ({
          year: parseInt(year),
          value: Math.round(values.reduce((a, b) => a + b, 0) / values.length)
        }))
        .sort((a, b) => a.year - b.year);

      result[key] = {
        name: dim.name,
        unit: dim.unit,
        description: dim.description,
        trend: analyzeTrend(yearlyData),
        summary: generateSummary(yearlyData, dim),
        data: yearlyData
      };
    }

    return result;
  } catch (error) {
    console.error('分析全国趋势时出错:', error);
    throw error;
  }
}

/**
 * 分析所有省份的发展趋势
 * @returns {Object} 包含所有省份各维度历年数据的对象
 */
async function analyzeAllProvincesTrend() {
  try {
    const provinces = await Province.find({});
    const result = [];
    
    for (const province of provinces) {
      result.push({
        name: province.name,
        data: await analyzeProvinceTrend(province.name),
      });
      // result[province.name] = await analyzeProvinceTrend(province.name);
    }
    
    return result;
  } catch (error) {
    console.error('分析所有省份趋势时出错:', error);
    throw error;
  }
}

export { analyzeProvinceTrend, analyzeNationalTrend, analyzeAllProvincesTrend }